package routines;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class DAO {

	protected static Session session = null;
	protected static Transaction transaction = null;

	public static void setSession(Session s) {
		session = s;
	}

	public static Session openSession() {
		if (session == null)
			session = HibernateUtil.openSession();
		return session;
	}

	protected static void CheckSession(String name) throws Exception {
		if (session == null)
			throw new Exception("Не установлена сессия в " + name);
	}

	protected static void CheckSession() throws Exception {
		if (session == null)
			throw new Exception("Не установлена сессия");
	}

	public static void CloseSession() {
		if (session != null) {
			HibernateUtil.closeSession(session);
			session = null;
		}
	}

	public static Object Save(Object o) {
		session.saveOrUpdate(o);
		return o;
	}

	public static void beginTransaction() throws Exception {
		CheckSession();
		if (transaction == null)
			transaction = session.beginTransaction();

	}

	public static void commit() {
		if (transaction != null)
			transaction.commit();
		transaction = null;
	}

	public static int executeSQLUpdate(String q) throws Exception {
		CheckSession();
		int res = session.createSQLQuery(q).executeUpdate();
		return res;
	}

}
